const { BASE_URL, TOKEN_STORAGE_KEY } = require('../config');
const auth = require('./auth');

const DEFAULT_ERROR = '服务繁忙，请稍后再试';

const clearAuth = () => {
  auth.clearAuth();
  // 更新全局认证状态
  const app = getApp();
  if (app) {
    app.setAuthState(false, null);
  }
};

const request = (options = {}) => {
  const {
    url = '',
    method = 'GET',
    data = {},
    header = {},
    showErrorToast = true,
    suppressAuth = false
  } = options;

  const token = suppressAuth ? '' : wx.getStorageSync(TOKEN_STORAGE_KEY);
  const headers = Object.assign(
    { 'Content-Type': 'application/json' },
    header,
    token ? { Authorization: `Bearer ${token}`, 'satoken': token } : {}
  );

  const requestUrl = url.startsWith('http') ? url : `${BASE_URL}${url}`;

  return new Promise((resolve, reject) => {
    wx.request({
      url: requestUrl,
      method,
      data,
      header: headers,
      success: async (res) => {
        const { statusCode, data: body = {} } = res;
        const payloadCode = body.code;
        const payloadMessage = body.message || DEFAULT_ERROR;

        if (statusCode === 401 || payloadCode === 401) {
          // 尝试自动刷新token
          try {
            const refreshSuccess = await auth.refreshToken();
            
            if (!refreshSuccess) {
              // 开发模式下，不自动清除token（避免误退出）
              try {
                const devConfig = require('../config/dev');
                const token = wx.getStorageSync(TOKEN_STORAGE_KEY);
                const isDevMode = devConfig && devConfig.enabled && token && token.startsWith('dev_token_');
                
                if (!isDevMode) {
                  clearAuth();
                  wx.showToast({ title: '登录已过期，请重新登录', icon: 'none' });
                  wx.reLaunch({ url: '/pages/login/login' });
                }
              } catch (e) {
                // 如果无法加载dev配置，使用默认行为
                clearAuth();
                wx.showToast({ title: '登录已过期，请重新登录', icon: 'none' });
                wx.reLaunch({ url: '/pages/login/login' });
              }
            } else {
              // token刷新成功，更新全局状态
              const app = getApp();
              if (app) {
                app.updateAuthState();
              }
              // 重新发起请求（可选，这里仅返回错误，由调用方决定是否重试）
            }
          } catch (error) {
            // 刷新token失败，清除认证信息
            clearAuth();
            wx.showToast({ title: '登录已过期，请重新登录', icon: 'none' });
            wx.reLaunch({ url: '/pages/login/login' });
          }
          reject(new Error('Unauthorized'));
          return;
        }

        if (statusCode < 200 || statusCode >= 300) {
          if (showErrorToast) {
            wx.showToast({ title: payloadMessage, icon: 'none' });
          }
          reject(new Error(payloadMessage));
          return;
        }

        if (payloadCode !== undefined && payloadCode !== 200) {
          if (showErrorToast) {
            wx.showToast({ title: payloadMessage, icon: 'none' });
          }
          reject(new Error(payloadMessage));
          return;
        }

        resolve({
          code: payloadCode ?? 200,
          message: body.message || '',
          data: body.data
        });
      },
      fail: (err) => {
        if (showErrorToast) {
          wx.showToast({ title: DEFAULT_ERROR, icon: 'none' });
        }
        reject(err);
      }
    });
  });
};

module.exports = {
  request,
  clearAuth
};
